package cn.yunhe.controller;

import cn.yunhe.model.*;
import cn.yunhe.service.ILiPeiService;
import cn.yunhe.utils.EmailUtil;
import cn.yunhe.utils.PeiFuJieSuanUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @创建人 项目二组 鲍康
 * @创建时间 2017/12/24
 * @描述
 */

@RestController
@RequestMapping("/lipei")
public class LipeiguanliAction {

    @Resource
    private ILiPeiService liPeiService;

    @RequestMapping("/tolipeidan-info")
    public ModelAndView tolipeidaninfo(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("lipeidan-info");
        return mv;
    }

    @RequestMapping("/tolipeidan-add")
    public ModelAndView tolipeidanadd(){
        ModelAndView mv = new ModelAndView();
         /*mv.addObject("un_id",session.getAttribute("un_id"));*/
        /*System.out.println(""+flag);
        mv.addObject("flag",flag);*/
        mv.setViewName("lipeidan-add");
        return mv;
    }

    @RequestMapping("/tolipeidan-list")
    public ModelAndView tolipeidanlist(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("redirect:/lipei/queryClaimant.do");
        return mv;
    }

    @RequestMapping("/tolipei-jiesuan")
    public ModelAndView tolipeijiesuan(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/lipei/querystate.do");
        return mv;
    }
    @RequestMapping("/tolipei-jilu")
    public ModelAndView tolipeijilu(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("redirect:/lipei/queryClairecord.do");
        return mv;
    }
    /**
     * 增加报案单
     */
   /* @RequestMapping("/addClaimant")
    public Result addClaimant(Claimant claimant, Users users, String addtime, Survey survey, String stime) throws ParseException,IOException{
        Map<String,Object> ma = new HashMap<String,Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行添加报案单");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("添加");//(添加，删除，修改)
        blog.setUn_id(1);


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date=sdf.parse(addtime);
            claimant.setCl_addtime(date);
            claimant.setUsers(users);

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date s_time=sdf1.parse(stime);
        survey.setS_time(s_time);

        ma.put("claimant",claimant);
        ma.put("blog",blog);
        ma.put("survey",survey);

        liPeiService.addClaimant(ma);
        liPeiService.addSurvey(ma);
        return new Result();
    }*/
    @RequestMapping("/addClaimant")
    public ModelAndView addClaimant(@RequestParam("msg_table") MultipartFile file, HttpServletRequest request,Claimant claimant ,LiPei liPei,Users users,HttpSession session,HttpSession myselfsession) throws ParseException,IOException {
        ModelAndView mv = new ModelAndView();
        //将users对象放到
        claimant.setUsers(users);
        String path1 = request.getServletContext().getRealPath("");//获取项目动态绝对路径
        //上传msg_table文件
        String filename = file.getOriginalFilename();
        file.getContentType();
        File dest = new File(filename);
        claimant.setMsg_table(filename);
        //添加日志信息
        Map<String,Object> ma = new HashMap<String,Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行添加报案单");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("添加");//(添加，删除，修改)
        UserNumber userNumber=(UserNumber) session.getAttribute("UsernumberRoleUsers");
        blog.setUn_id(userNumber.getUn_id());

    /*ma.put("claimant",claimant);*/
        ma.put("blog",blog);
        //上传文件
        file.transferTo(dest);
        List <Integer> baoxian = liPei.getCi_id();

        List<CarInsur> list = liPeiService.queryCarInsur(baoxian);
        BigDecimal qiangxianMony = null;
        PeiFuJieSuanUtil pfjs = new PeiFuJieSuanUtil();

        int un_id=userNumber.getUn_id();
        claimant.setUn_id(un_id);
        String c_id = claimant.getC_id();
        Cars cars = liPeiService.queryCarById(c_id);

        BigDecimal shangwang = new BigDecimal(0);
        BigDecimal yiliao = new BigDecimal(0);
        BigDecimal caichan = new BigDecimal(0);
        int flag=0;
        for (CarInsur ci:list) {
            //机动车交通事故责任强制保险
            if("机动车交通事故责任强制保险".equals(ci.getCi_name())){
                //String c_id, Users users, CarInsur carInsur, int sgzr, double jdmp, double cl_type, int un_id, Date cl_addtime, BigDecimal cl_money, BigDecimal cl_money1, BigDecimal cl_money2, BigDecimal zonghe, BigDecimal dsf_money, String clds_type, String msg_table
                Map<String,BigDecimal> map = pfjs.qiangZhiJieSuan(liPei.getCl_money(),liPei.getCl_money1(),liPei.getCl_money2(),liPei.getSgzr());//map.put("sishang",peiFu1);map.put("yiliao",peiFu2);map.put("caichan",peiFu3);
                Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),new CarInsur(ci.getCi_id()),liPei.getSgzr(),0.0,claimant.getCl_type(),claimant.getUn_id(),new Date(),map.get("sishang"),map.get("yiliao"),map.get("caichan"),map.get("he"),liPei.getDsf_money(),claimant.getClds_type(),filename);
                qiangxianMony = map.get("he");
                System.out.println(map.get("peiFu1"));
                shangwang = liPei.getCl_money().subtract(map.get("sishang"));
                yiliao = liPei.getCl_money1().subtract(map.get("yiliao"));
                caichan = liPei.getCl_money2().subtract(map.get("caichan"));
                ma.put("claimant",cl);
                liPeiService.addClaimant(ma);

            }else if("机动车损失保险".equals(ci.getCi_name())){
                //机动车损失保险
                BigDecimal cheLiangSunShi = pfjs.cheSunJieSuan(caichan,ci.getMaxmoney(),liPei.getDsf_money(),liPei.getJdmpe(),liPei.getSgzr(),liPei.getJdmp_cs(),liPei.getCategory(),cars);
//               Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),claimant.getCl_type(),claimant.getCl_state(),1,new Date(),0,0,new BigDecimal(0),new BigDecimal(0),cheLiangSunShi,filename);
                Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),new CarInsur(ci.getCi_id()),liPei.getSgzr(),liPei.getJdmp_cs(),claimant.getCl_type(),claimant.getUn_id(),new Date(),new BigDecimal(0),new BigDecimal(0),cheLiangSunShi,cheLiangSunShi,liPei.getDsf_money(),claimant.getClds_type(),filename);
                ma.put("claimant",cl);
                caichan = caichan.subtract(cheLiangSunShi);
                liPeiService.addClaimant(ma);
            }else if("机动车全车盗抢保险".equals(ci.getCi_name())){
                //机动车全车盗抢保险
                BigDecimal daoQiangXian = pfjs.daoQiangJieSuan(caichan,ci.getMaxmoney(),liPei.getJdmp_dq(),liPei.getCategory(),cars);
                //Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),claimant.getCl_type(),claimant.getCl_state(),1,new Date(),0,0,new BigDecimal(0),new BigDecimal(0),daoQiangXian,filename);
                Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),new CarInsur(ci.getCi_id()),liPei.getSgzr(),liPei.getJdmp_dq(),claimant.getCl_type(),claimant.getUn_id(),new Date(),new BigDecimal(0),new BigDecimal(0),daoQiangXian,daoQiangXian,liPei.getDsf_money(),claimant.getClds_type(),filename);
                ma.put("claimant",cl);
                caichan.subtract(daoQiangXian);
                liPeiService.addClaimant(ma);
            }else if("机动车车上人员责任保险".equals(ci.getCi_name())){
                //机动车车上人员责任保险
                BigDecimal cheShangRenYuan = pfjs.renYuanJieSuan(ci.getMaxmoney(),liPei.getZwss(),yiliao,claimant.getCl_type(),liPei.getSgzr());
                BigDecimal zonghe = cheShangRenYuan.multiply(new BigDecimal(cars.getSeatnum()));
                Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),new CarInsur(ci.getCi_id()),liPei.getSgzr(),liPei.getJdmp_dq(),claimant.getCl_type(),claimant.getUn_id(),new Date(),cheShangRenYuan,new BigDecimal(0),new BigDecimal(0),zonghe,liPei.getDsf_money(),claimant.getClds_type(),filename);
                ma.put("claimant",cl);
                liPeiService.addClaimant(ma);
            }else if("机动车第三者责任保险".equals(ci.getCi_name())){
                //机动车第三者责任保险
                BigDecimal disanzhe =pfjs.DiSanZhe(ci.getMaxmoney(),liPei.getPeifu_dsf(),claimant.getCl_type(),liPei.getSgzr(),liPei.getJdmp_ds());
                //Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),claimant.getCl_type(),claimant.getCl_state(),1,new Date(),0,0,disanzhe,new BigDecimal(0),new BigDecimal(0),filename);
                Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),new CarInsur(ci.getCi_id()),liPei.getSgzr(),liPei.getJdmp_dq(),claimant.getCl_type(),claimant.getUn_id(),new Date(),disanzhe,new BigDecimal(0),new BigDecimal(0),disanzhe,liPei.getDsf_money(),claimant.getClds_type(),filename);
                ma.put("claimant",cl);
                liPeiService.addClaimant(ma);
            }else{
                BigDecimal money = pfjs.qiTaJieSuan(liPei.getCl_money().add(liPei.getCl_money1().add(liPei.getCl_money2())),ci.getMaxmoney(),0.0);
                //Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),claimant.getCl_type(),claimant.getCl_state(),1,new Date(),0,0,money,new BigDecimal(0),new BigDecimal(0),filename);
                Claimant cl = new Claimant(claimant.getC_id(),claimant.getUsers(),new CarInsur(ci.getCi_id()),liPei.getSgzr(),liPei.getJdmp_dq(),claimant.getCl_type(),claimant.getUn_id(),new Date(),money,new BigDecimal(0),new BigDecimal(0),money,liPei.getDsf_money(),claimant.getClds_type(),filename);
                ma.put("claimant",cl);
                liPeiService.addClaimant(ma);
            }
            flag=1;
           /*myselfsession.setAttribute("msg2","添加成功");*/
            mv.addObject("msg1","添加成功");
        }
        //改变用户出险次数
        Map<String,Object> m = new HashMap<String,Object>();
        Busilog b=new Busilog();//日志信息的描述
        b.setLog_busimasg("进行修改车辆出险次数");//简单的业务描述
        b.setLog_addtime(new Date());
        b.setLog_busitype("修改");//(添加，删除，修改)
        b.setUn_id(userNumber.getUn_id());

        ma.put("claimant",claimant);
        m.put("blog",b);
        m.put("c_id",claimant.getC_id());
        liPeiService.editCarChuxianNum(m);
        mv.setViewName("forward:/lipei/tolipeidan-add.do");
        return mv;
    }

    /**
     * 查询全部报案单
     * @return
     */
    @RequestMapping("/queryClaimant")
    public ModelAndView queryClaimant(){
        List<Claimant> list=liPeiService.queryClaimant();
        ModelAndView mv=new ModelAndView();
        mv.addObject("claimantlist",list);
        mv.setViewName("lipeidan-list");
        return mv;
    }
    /**
     * 通过车牌号得到车辆信息
     */

    @RequestMapping("/queryCarById")
    public ModelAndView queryCarById(String c_id){
        Cars cars=liPeiService.queryCarById(c_id);
        ModelAndView mv=new ModelAndView();
        boolean flag = true;
        if(null==cars){
            flag = false;
        }else {
            List<InsurContract> icon=liPeiService.queryInsurContractById(c_id);

            mv.addObject("icon",icon);
            mv.addObject("cars",cars);
            flag = true;
        }
        mv.addObject("flag",flag);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }



    /**
     * 上传文件
     * @return
     */
    @RequestMapping("/upfile")
    public ModelAndView upfile(@RequestParam(name = "file") MultipartFile file){
        ModelAndView mv=new ModelAndView();
        //获取文件原始名
        String filename=file.getOriginalFilename();
        file.getContentType();
        //目标地址
        File dest=new File(filename);


        try{
            file.transferTo(dest);
            mv.addObject("succ",true);
            mv.addObject("msg","上传成功");
            mv.setViewName("lipeidan-info");
        }catch (IOException e){
            mv.addObject("succ",true);
            mv.addObject("msg","上传失败");
            e.printStackTrace();
        }
        return  mv;

    }

    /**
     * 下载文件
     * @param agent
     * @return
     * @throws Exception
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(@RequestHeader("User-Agent") String agent)throws Exception{

        File file=new File("C:\\Users\\Administrator\\IdeaProjects\\AnKangBaoXian\\src\\main\\webapp\\uploadsFile\\理赔申请书.docx");
        //设置响应的说明和额外的参数
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //由注解@RequestHeader("User-Agent")获取到浏览器的类型来解决中文乱码的问题（因为浏览器的兼容性不同）
        String filename = "";
        if (agent.toUpperCase().contains("CHROME")) {
            filename = new String(file.getName().getBytes("utf-8"),"iso-8859-1");
        }else if (agent.toUpperCase().contains("MSIE")) {
            filename = new String(file.getName().getBytes("iso-8859-1"),"utf-8");
        }

        headers.setContentDispositionFormData("attachment", filename);

        //将文件转成byte数组
        byte[] by = FileUtils.readFileToByteArray(file);
        //三个参数分别是一个文件的byte数组，头部信息以及响应码（201）
        ResponseEntity<byte[]> rn = new ResponseEntity<byte[]>(by,headers, HttpStatus.CREATED);
        return rn;
    }
    /**
     * 下载详细报案表
     */

    @RequestMapping("/downloadMsgTable")
    public ResponseEntity<byte[]> downloadMsgTable(@RequestHeader("User-Agent") String agent,String msgtable)throws Exception{
        File file=new File("C:\\Users\\Administrator\\IdeaProjects\\AnKangBaoXian\\src\\main\\webapp\\uploadsFile\\"+msgtable);
        //设置响应的说明和额外的参数
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //由注解@RequestHeader("User-Agent")获取到浏览器的类型来解决中文乱码的问题（因为浏览器的兼容性不同）
        String filename = "";
        if (agent.toUpperCase().contains("CHROME")) {
            filename = new String(file.getName().getBytes("utf-8"),"iso-8859-1");
        }else if (agent.toUpperCase().contains("MSIE")) {
            filename = new String(file.getName().getBytes("iso-8859-1"),"utf-8");
        }
        ResponseEntity<byte[]> rn=null;
        try{
            headers.setContentDispositionFormData("attachment", filename);
            //将文件转成byte数组
            byte[] by = FileUtils.readFileToByteArray(file);
            //三个参数分别是一个文件的byte数组，头部信息以及响应码（201）
            rn = new ResponseEntity<byte[]>(by,headers, HttpStatus.CREATED);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
            String  path = "C:\\Users\\Administrator\\IdeaProjects\\AnKangBaoXian\\src\\main\\webapp\\uploadsFile\\1.jpg";
            file = new File(path);
            headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //由注解@RequestHeader("User-Agent")获取到浏览器的类型来解决中文乱码的问题（因为浏览器的兼容性不同）
            if (agent.toUpperCase().contains("CHROME")) {
                filename = new String(file.getName().getBytes("utf-8"),"iso-8859-1");
            }else if (agent.toUpperCase().contains("MSIE")) {
                filename = new String(file.getName().getBytes("iso-8859-1"),"utf-8");
            }
            headers.setContentDispositionFormData("attachment", filename);
            //将文件转成byte数组
            byte[] by = FileUtils.readFileToByteArray(file);
            //三个参数分别是一个文件的byte数组，头部信息以及响应码（201）
            rn = new ResponseEntity<byte[]>(by,headers, HttpStatus.CREATED);
        }finally {
            return rn;
        }

    }
    /**
     * 查询理赔信息
     * @return
     */
    @RequestMapping("/querystate")
    public ModelAndView querystate(){
        List<LiPeiJieSuan> list=liPeiService.querystate();
        ModelAndView mv=new ModelAndView();
        mv.addObject("statelist",list);
        mv.setViewName("lipei-jiesuan");
        return mv;
    }

    /**
     * 结算
     * @param claimant
     * @return
     */
    @RequestMapping("/edit_jiesuan")
    public ModelAndView edit_jiesuan(Claimant claimant,HttpSession session){
        ModelAndView mv = new ModelAndView();
        EmailUtil emailUtil=new EmailUtil();
        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行理赔结算");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("修改");//(添加，删除，修改)
        UserNumber userNumber=(UserNumber) session.getAttribute("UsernumberRoleUsers");
        blog.setUn_id(userNumber.getUn_id());
        ma.put("blog",blog);

        System.out.println("车牌是"+claimant.getC_id());
        ClaiRecord claiRecord = new ClaiRecord();
        List<Claimant> claimants=liPeiService.queryClaimantById(claimant.getC_id(),claimant.getCl_jiesuan());
        for(Claimant cl:claimants){
            claimant.setCl_id(cl.getCl_id());
            ma.put("claimant",claimant);
            liPeiService.edit_jiesuan(ma);
            emailUtil.send_qqmail(cl.getUsers().getU_emal(), "理赔到账提醒", "尊敬的用户您的车牌为"+cl.getC_id()+"的<"+cl.getCarInsur().getCi_name()+">赔付款已结算，请查收。中国安康车险祝您新年快乐，幸福安康！");
            //添加理赔记录
            claimant.setCl_id(cl.getCl_id());
            claimant.setZonghe(cl.getZonghe());
            ma.put("claimant",claimant);
            claiRecord.setUserNumber(userNumber);
            claiRecord.setClaimant(claimant);
            claiRecord.setCla_addtime(new Date());
            ma.put("claiRecord",claiRecord);
            liPeiService.addClairecord(ma);
        }
        /*List<LiPeiJieSuan> list=liPeiService.querystate();
        for (LiPeiJieSuan liPeiJieSuan:list){
            emailUtil.send_qqmail(liPeiJieSuan.getU_emal(), "理赔到账提醒", "尊敬的用户您的车牌为"+liPeiJieSuan.getC_id()+"的赔付款已结算，请查收。中国安康车险祝您新年快乐，幸福安康！");
        }*/
        int flag = liPeiService.edit_jiesuan(ma);
        mv.addObject("flag",flag);



        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    /**
     * 添加结算记录
     * @return
     */
    @RequestMapping("/addClairecord")
    public ModelAndView addClairecord(ClaiRecord claiRecord,Claimant claimant,HttpSession session){
        ModelAndView mv=new ModelAndView();
        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("添加理赔记录");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("添加");//(添加，删除，修改)
        blog.setUn_id(1);
        ma.put("blog",blog);
        UserNumber userNumber=(UserNumber) session.getAttribute("UsernumberRoleUsers");
        System.out.println(userNumber);
       /* if (session.getAttribute("UsernumberRoleUsers.un_id")!=null){
            int id=Integer.parseInt(session.getAttribute("UsernumberRoleUsers.un_id").toString());
            userNumber.setUn_id(id);
            userNumber.setUn_pwdsalt("UsernumberRoleUsers.un_pwdsalt");
            claiRecord.setUserNumber(userNumber);
        }*/
        List<Claimant> claimants=liPeiService.queryClaimantById(claimant.getC_id(),claimant.getCl_jiesuan());
        for(Claimant cl:claimants){
            claimant.setCl_id(cl.getCl_id());
            claimant.setZonghe(cl.getZonghe());
            ma.put("claimant",claimant);
            claiRecord.setUserNumber(userNumber);
            claiRecord.setClaimant(claimant);
            claiRecord.setCla_addtime(new Date());
            ma.put("claiRecord",claiRecord);
            liPeiService.addClairecord(ma);
        }

        mv.setView(new MappingJackson2JsonView());
        return mv;
    }


    /**
     * 查询全部理赔记录
     * @return
     */
    @RequestMapping("/queryClairecord")
    public ModelAndView queryClairecord(){
        List<ClaiRecord> list=liPeiService.queryClaiRecord();
        ModelAndView mv=new ModelAndView();
        mv.addObject("claiRecordlist",list);
        mv.setViewName("lipeijiludan-list");
        return mv;
    }

    /**
     * 通过ID得到保险信息
     */

    @RequestMapping("/queryClaimantById")
    public ModelAndView querycarInsurById(Claimant claimant){
        ModelAndView mv=new ModelAndView();
        List<Claimant> claimants=liPeiService.queryClaimantById(claimant.getC_id(),claimant.getCl_jiesuan());
        mv.addObject("claimants",claimants);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }
    public ILiPeiService getLiPeiService() {
        return liPeiService;
    }

    public void setLiPeiService(ILiPeiService liPeiService) {
        this.liPeiService = liPeiService;
    }
}
